'user strict'
var socket;
var localVideo = document.querySelector("video#localVideo")
var localStream;
var localPC;
var muted = false;
var openVideo = true;
var isShare = false;
var isInRoom = false;
var simulcast = true;
var mirc = document.querySelector("img#mirc")
var camera = document.querySelector("img#camera")
var share = document.querySelector("img#share")
var startOrPauseButton = document.querySelector("img#startOrPause")
function handlerError(err) {
    console.log(err.name + ":" + err.message);
}
function sleep(numberMillis) {
    var now = new Date();
    var exitTime = now.getTime() + numberMillis;
    while (true) {
        now = new Date();
        if (now.getTime() > exitTime)
            return;
    }
}
async function changeDisplay() {
    localStream = await navigator.mediaDevices.getDisplayMedia({
        video: true
    });
    isShare = true;
    share.src = "../icon/share-on.svg";
    if (openVideo) {
        openVideo = !openVideo;
        camera.src = "../icon/video-off.svg"
    }
    changeMedia();
}
function changeMedia() {
    localVideo.srcObject = localStream;
    let videoTrack = localStream.getVideoTracks()[0];
    var sender = localPC.getSenders().find(function (s) {
        return s.track.kind == videoTrack.kind;
    });
    console.log('found sender:', sender);
    sender.replaceTrack(videoTrack);
}
async function changeUserCamera() {
    localStream = await navigator.mediaDevices.getUserMedia({
        video: {
            facingMode: "user"
        },
        audio: {
            echoCancellation: true,
            noiseSuppression: true
        }
    });
    changeMedia();
}
async function changeEnvironmentCamera() {
    localStream = await navigator.mediaDevices.getUserMedia({
        video: {
            facingMode: "environment"
        },
        audio: {
            echoCancellation: true,
            noiseSuppression: true
        }
    });
    changeMedia();
}
async function initPeerConnection(name, upload) {
    var pc = new RTCPeerConnection(configuration);
    if (!localStream) {
        localStream = await navigator.mediaDevices.getUserMedia({
            video: { width: 1600, height: 900 },
            audio: {
                echoCancellation: true,
                noiseSuppression: true
            }
        });
        localVideo.srcObject = localStream;
        console.log("get local media:")
        console.log(localStream)
    }

    for (const track of localStream.getTracks()) {
        if (upload) {
            pc.addTrack(track, localStream);
        }
    }
    pc.onicecandidate = (e) => {
        if (e.candidate) {
            sendCandidate(name, e.candidate)
            console.log("you have send candidate " + name)
            console.log(e.candidate)
        }
    }
    return pc;
}
function initLocalWebRtc() {
    initPeerConnection(id, true).then(function (res) {
        localPC = res;
        var offerOptions = {
            iceRestart: true,
            offerToReceiveAudio: false,
            offerToReceiveVideo: false,
        }
        localPC.createOffer(offerOptions).then(function (offer) {
            console.log("you createOffer:")
            console.log(offer)
            if(simulcast){
                offer.sdp = mungeSdpForSimulcasting(offer.sdp)
            }
            console.log("you mungeSdpForSimulcasting:")
            console.log(offer)
            return localPC.setLocalDescription(offer);
        }).then(function () {
            sendOffer(localPC.localDescription);
        }).catch(handlerError);
    });
    keepalive();
}
function connect() {
    // 判断当前浏览器是否支持webSocket
    if (window.WebSocket) {
        socket = new WebSocket(wsUrl);
        // 相当于channel的read事件，ev 收到服务器回送的消息
        socket.onmessage = function (ev) {
            if (ev.data) {
                var data = ev.data;
                if (ev.data == "Connected") {
                    console.log("登陆成功");
                    joinAndPub();
                    return;
                }
                data = JSON.parse(data);
                const response = JSON.stringify(data);
                console.log(response)
                if (data.jsep) {
                    var jsep = data.jsep;
                    if (jsep.type == "answer") {
                        localPC.setRemoteDescription(new RTCSessionDescription(jsep));
                        console.log("set remote description" + jsep)
                        return;
                    }
                    if (jsep.type == "offer") {
                        var plugindata = data.plugindata;
                        var data = plugindata.data;
                        var display = data.display;
                        initPeerConnection(display, false).then(function (res) {
                            var pc = res;
                            pc.setRemoteDescription(new RTCSessionDescription(jsep))
                            var answerOptions = {
                                iceRestart: true,
                                answerToReceiveAudio: true,
                                answerToReceiveVideo: true,
                            }
                            pc.createAnswer(answerOptions).then(function (offer) {
                                console.log("you createAnswer:")
                                console.log(offer)
                                return pc.setLocalDescription(offer);
                            }).then(function () {
                                start(pc.localDescription, display)
                                pcMap.set(display, pc);
                                console.log("you have received offer from " + display)
                            }).catch(handlerError);
                        });
                        return;
                    }
                }
                if (data.janus == "event") {
                    data = data.plugindata;
                    data = data.data;
                    if (data.videoroom == "joined") {
                        initLocalWebRtc();
                    }
                }
            }
        }
        // 相当于连接开启
        socket.onopen = function (ev) {
            if(!id){
                id = uuid2(16, 16)
            }
            login()
        }
        // 相当于连接关闭
        socket.onclose = function (ev) {
            logout()
        }
    } else {
        alert("当前浏览器不支持webSocket")
    }
}
function changeMuted() {
    if (muted) {
        mirc.src = "../icon/mirc-on.svg"
    } else {
        mirc.src = "../icon/mirc-off.svg"
    }
    muted = !muted;
    doMuted()
}
function changeCamera() {
    if (openVideo) {
        camera.src = "../icon/video-off.svg"
    } else {
        if (isShare) {
            isShare = !isShare;
            share.src = "../icon/share-off.svg"
            changeUserCamera();
        }
        camera.src = "../icon/video-on.svg"
    }
    openVideo = !openVideo;
    doOpenOrCloseCamera()
}
function doMuted() {
    localVideo.srcObject = localStream;
    let audioTrack = localStream.getAudioTracks()[0];
    var sender = localPC.getSenders().find(function (s) {
        return s.track.kind == audioTrack.kind;
    });
    audioTrack.enabled = muted;
    console.log('found sender:', sender);
    sender.replaceTrack(audioTrack);
}
function doOpenOrCloseCamera() {
    localVideo.srcObject = localStream;
    let videoTrack = localStream.getVideoTracks()[0];
    var sender = localPC.getSenders().find(function (s) {
        return s.track.kind == videoTrack.kind;
    });
    videoTrack.enabled = openVideo;
    console.log('found sender:', sender);
    sender.replaceTrack(videoTrack);
}
function startOrPause() {
    if (isInRoom) {
        stoplive();
        startOrPauseButton.src = "../icon/start.svg"
        isInRoom = false;
    } else {
        isInRoom = true;
        startlive();
        startOrPauseButton.src = "../icon/stop.svg"
    }
}
function prom() {
    room = getQueryVariable("room")
    if(getQueryVariable("simulcast")){
        simulcast = getQueryVariable("simulcast")
    };
    if (room) {
        connect();
    } else {
        id = uuid2(16, 16)
        room = Math.floor(Math.random() * (360000) + 1000)
        window.location.href = "?room=" + room
    }
}
prom();
mirc.onclick = changeMuted
share.onclick = changeDisplay
camera.onclick = changeCamera
startOrPauseButton.onclick = startOrPause
// environment.onclick = changeEnvironmentCamera